import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet( "/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int width = 100;
        int height = 50;

        //创建一对象，在内存中图片（验证码图片对象）
        BufferedImage image = new BufferedImage(width,height,1);

        //美化图片
        Graphics g=image.getGraphics();//画笔对象
        g.setColor(Color.pink);
        g.fillRect(0,0,width,height);
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width-1,height-1);

        String str="QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789";
        //生成随机角标
        Random ran = new Random();

        //写验证码
        for (int i = 1; i < 5; i++) {
            int index = ran.nextInt(str.length());
            char c = str.charAt(index);//随机字符
            g.drawString(c+"",width/5*i,height/2);
        }

        //划干扰线
        g.setColor(Color.GREEN);
        //随机生成坐标点
        for (int i = 0; i < 8; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);
            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }

        //将图片输出到页面
        ImageIO.write(image,"jpg",response.getOutputStream());

    }
}
